package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.LogBean;
import com.project.bean.PermissionBean;
import com.project.bean.RoleBean;
import com.project.bean.UserBean;
import com.project.mapper.ILogMapper;
import com.project.mapper.IPermissionMapper;
import com.project.mapper.IRoleMapper;
import com.project.mapper.IUserMapper;
import com.project.service.IUserService;
import io.swagger.models.auth.In;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Service
@Transactional
public class UserServiceImpl implements IUserService {
    @Autowired
    private IUserMapper userMapper;
    @Autowired
    private ILogMapper logMapper;
    @Autowired
    private IPermissionMapper permissionMapper;

    @Autowired
    private IRoleMapper roleMapper;

    @Override
    public UserBean login(String userName, String pwd) {
        UserBean login = userMapper.login(userName, pwd);
        if (login != null) {
            //添加日志
            logMapper.insert(new LogBean(userName));

            List<RoleBean> roleList = login.getRoleList();
            Integer[] arr = new Integer[roleList.size()];
            for (int i = 0; i < arr.length; i++) {
                arr[i] = roleList.get(i).getId();
            }
            List<PermissionBean> byRoleIdArray = permissionMapper.findByRoleIdArray(arr);
            login.setPermissionList(byRoleIdArray);
        }
        return login;
    }

    @Override
    public IPage<UserBean> findByItem(Integer pageNO, String name) {
        QueryWrapper<UserBean> qw = new QueryWrapper<>();
        qw.eq("u_status", "在职");
        if (name != null && name.length() != 0) {
            qw.like("u_name", name);
        }
        return userMapper.selectPage(new Page<>(pageNO, 3), qw);
    }

    @Override
    public UserBean findByName(String name) {
        QueryWrapper<UserBean> qw = new QueryWrapper<>();
        qw.eq("u_name", name);
        UserBean userBean = userMapper.selectOne(qw);
        if (userBean != null && "在职".equals(userBean.getStatus())) {
            //查询角色集合
            List<RoleBean> roleList = roleMapper.findByUser(userBean.getId());
            userBean.setRoleList(roleList);
            //定义一个roleId数组，把根据用户查询到的roleId放入改数组
            Integer[] arr = new Integer[roleList.size()];
            for (int i = 0; i < arr.length; i++) {
                //遍历赋值
                arr[i] = roleList.get(i).getId();
            }
            //查询权限集合
            List<PermissionBean> permissionList = permissionMapper.findByRoleIdArray(arr);
            userBean.setPermissionList(permissionList);
            return userBean;
        }
        return userBean;
    }

    @Override
    public void add(UserBean user, Integer... roleIdArray) {
        //盐
        user.setSalt(this.getSalt());
        Md5Hash md5Hash = new Md5Hash(user.getPwd(), user.getSalt(), 1024);
        //加密后的密码
        user.setPwd(md5Hash.toHex());
        //添加用户
        userMapper.insert(user);
        //添加用户角色中间表关系
        userMapper.add(user.getId(), roleIdArray);
    }

    @Override
    public void del(Integer userId) {
        userMapper.delByUserId(userId);
        userMapper.update(userId);
    }

    @Override
    public UserBean findById(Integer id) {
        UserBean byId = userMapper.findById(id);
        List<RoleBean> roleList = byId.getRoleList();
        Integer[] arr = new Integer[roleList.size()];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = roleList.get(i).getId();
        }
        List<PermissionBean> byRoleIdArray = permissionMapper.findByRoleIdArray(arr);
        byId.setPermissionList(byRoleIdArray);
        return byId;
    }

    @Override
    public void updateRole(Integer userId, Integer... newRoleArray) {
        userMapper.delByUserId(userId);
        userMapper.add(userId, newRoleArray);
    }

    @Override
    public void updatePwd(Integer userId, String newPwd) {
        UserBean userBean = userMapper.selectById(userId);
        //加盐
        Md5Hash md5Hash = new Md5Hash(newPwd,userBean.getSalt(),1024);
        //加密后的密码
        userBean.setPwd(md5Hash.toHex());
        userMapper.updateById(userBean);
    }

    @Override
    public UserBean findByUserId(Integer userId) {
        return userMapper.findById(userId);
    }


    private String getSalt() {
        String str = "abcdefghijklmnobqrsduvwxyzABCDEFGHIJKLMNOBQRSTUVWXYZ";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            Random r = new Random();
            int index = r.nextInt(str.length());
//            int index = (int) (Math.random() * str.length());
            sb.append(str.charAt(index));
        }
        return sb.toString();
    }
}
